/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import dataentry.Form;
import dataentry.FormFactory;
import dataentry.Persistence;
import dataentry.Question;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.KeyboardFocusManager;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

/**
 *
 * @author i.capurro
 */
public class DataInsert extends javax.swing.JPanel implements KeyListener, FocusListener {

    private Form f = null;
    private List list = null;
    private int it = 0;
    private JTextField data = null;
    private int posX = 60;
    private int posY = 5;
    private int height =  30;
    private int width =  60;
    private int separatorX = 30;
    private int separatorY = 10;
    private List responses = null;
    private List numbers = null;
    private Program prog = null;
    private FormFactory Factory = null;
    private int position;
    private int MAXposition;
    private String fname;
    private String path;
    private boolean alpha = false;
    
    /**
     * Creates new form DataInsert
     */
    
    private Component getFocus() {
    // Find focus owner
        Component c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();

        return c;
    }
    
    public DataInsert(String name, String path) {
        try {
            initComponents();
            fname = name;
            this.path = Persistence.getInstance().getPath();
            Persistence p = Persistence.getInstance();
            responses = new ArrayList();
            numbers = new ArrayList();
            startForm();
            
            p.createTable(fname,f.getFormHeader());
            
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null,ex);
        }
        
    }
    
    public void setAlpha(boolean set) {
        this.alpha = set;
    }
            
    
    private void startForm() throws FileNotFoundException, IOException, Exception {
        Factory = new FormFactory(fname, path);

        f = Factory.getForm();

        list = f.getQuestionsList();
        
        it = 0;
        
        Question ds = (Question) list.get(it);

        qName.setText("Número de Formulario");
        generateBoxes(ds.getLength());
    }
    
    private void deleteBoxes() {
        if (!responses.isEmpty()) {
            for (int i = 0; i < responses.size();i++) {
                JTextField response = (JTextField) responses.get(i);
                response.setVisible(false);
                panel.remove(response);
                JLabel number = (JLabel) numbers.get(i);
                panel.remove(number);
            }
            panel.repaint();
            responses.clear();
            numbers.clear();
        }
    }
    
    private void generateBoxes(int length) {
        
        deleteBoxes();
        
        char c = 'A';
        int p = (int)c;
        
        int y = posY;
        
        position = 0;
        
        for (int i = 0; i < length;i++) {
            JTextField response = new JTextField();
            response.setBounds(posX, y, width, height);
            JLabel number = new JLabel();
            number.setBounds(posX - separatorX, y, width/2, height);
            y = y + height + 5;
            
            if (length > 1) {
                if (alpha) {
                    number.setText("" + (char)(p+i));
                } else {
                    number.setText(Integer.toString(i+1));
                }
            }
            panel.add(response);
            if (i == 0) {
                response.requestFocus();
            }
            panel.add(number);
            response.addKeyListener(this);
            responses.add(response);
            numbers.add(number);
        }
        int panelHeight = responses.size()*(height+separatorY) + posY;
        int panelWidth = separatorX*2 + posX + width;
        panel.setPreferredSize(new Dimension(panelWidth, panelHeight));
        panel.repaint();
        MAXposition = length;
    }
    
    private void next() {
        if (it < (list.size())) {
            try {
                for (int i=0; i < responses.size(); i++) {
                    data = (JTextField) responses.get(i);
                    if (!data.getText().isEmpty()) {
                        Question q = (Question) list.get(it);
                        if (q.isValidValue(data.getText())) {
                            q.pushAnswer(data.getText());
                        } else {
                            q.emptyAnswers();
                            throw new Exception(data.getText() + " no es una valor valido para " + q.getName());
                        }
                        if (it == 0) {
                        Persistence p = Persistence.getInstance();
                            if (!p.validateID(data.getText(), f.getName())) {
                                throw new Exception("Número de formulario duplicado " + data.getText());
                            }
                        }
                    } else {
                        Question q = (Question) list.get(it);
                        if (q.isNotEmpty()) {
                            throw new Exception(q.getName() + " no admite campos vacios");
                        }
                    }
                }
                Question q = (Question) list.get(it);
                if (q.getAnswers().size() == 0) {
                    throw new Exception(q.getName() + " debe tener respuesta/s");
                }
                Question ds = null;
                boolean Display = false;
                while ((!Display) && (it < (list.size()-1))) {
                    it++;
                    ds = (Question) list.get(it);
                    Display = f.isDisplayableQuestion(ds.getName());
                }
                if (Display) {
                    qName.setText(ds.getName());
                    generateBoxes(ds.getLength());
                } else {
                    int confirmado = JOptionPane.showConfirmDialog(this,"¿Confirmas Guardado?");
                    if (JOptionPane.OK_OPTION == confirmado) {
                        f.save();
                        startForm();
                    } else if (JOptionPane.NO_OPTION == confirmado) {
                        startForm();
                    }
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null,ex);
            }
        } 
    }
    
    private void back() {
        if (it > 0) {
            try {
                Question ds = (Question) list.get(it);
                boolean Display = false;
                    while ((!Display) && (it > 0)) {
                        it--;
                        ds = (Question) list.get(it);
                        Display = f.isDisplayableQuestion(ds.getName());
                    }
                    if (!Display) {
                        ds = (Question) list.get(it);
                    }
                    if (it == 0) {
                        qName.setText("Número de Formulario");
                    } else {
                        qName.setText(ds.getName());
                    }
                    generateBoxes(ds.getLength());
                    Iterator answer = ds.getAnswers().iterator();
                    int i = 0;
                    while (answer.hasNext()) {
                        data = (JTextField) responses.get(i);
                        String ans = (String) answer.next();
                        data.setText(ans);
                        i++;
                    }
                    ds.emptyAnswers();
            } catch (Exception ex) {
                Logger.getLogger(DataInsert.class.getName()).log(Level.SEVERE, null, ex);
            }
        } 
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        qName = new javax.swing.JLabel();
        scrollPane = new javax.swing.JScrollPane();
        panel = new javax.swing.JPanel();

        qName.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        qName.setText("Pregunta");

        scrollPane.setAutoscrolls(true);

        javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
        panel.setLayout(panelLayout);
        panelLayout.setHorizontalGroup(
            panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 361, Short.MAX_VALUE)
        );
        panelLayout.setVerticalGroup(
            panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 299, Short.MAX_VALUE)
        );

        scrollPane.setViewportView(panel);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(scrollPane)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(qName)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(qName)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(scrollPane)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_ENTER) {
            next();
        }
        if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
            back();
        }
        if ((e.getKeyCode() == KeyEvent.VK_DOWN) || (e.getKeyCode() == KeyEvent.VK_RIGHT)) {
            position = (position+1) % MAXposition;
            JTextField jtext = (JTextField) responses.get(position);
            jtext.requestFocus();
        }
        if ((e.getKeyCode() == KeyEvent.VK_UP) || (e.getKeyCode() == KeyEvent.VK_LEFT)) {
            position = (position-1) % MAXposition;
            if (position < 0) {
                position = MAXposition + position;
            }
            JTextField jtext = (JTextField) responses.get(position);
            jtext.requestFocus();
        }
        Component c = getFocus();
        if ( c != null) {
            scrollPane.scrollRectToVisible(c.getBounds());
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel panel;
    private javax.swing.JLabel qName;
    private javax.swing.JScrollPane scrollPane;
    // End of variables declaration//GEN-END:variables

    @Override
    public void focusGained(FocusEvent e) {
        
        scrollPane.scrollRectToVisible((e.getComponent()).getBounds());
    }

    @Override
    public void focusLost(FocusEvent e) {
    }
}
